import axios from 'axios'
import type { ResultData } from '@/types/request'
import { useParamStore } from '@/stores';
import DialogTool from '@/util/DialogTool';
axios.defaults.withCredentials = true
axios.defaults.maxRedirects = 0;


//创建实例
export const fileService = axios.create({
  baseURL: '/oa.attach/',
  maxRedirects:0,
  validateStatus: function (status) {
    // 这里可以自定义哪些状态码被认为是成功的
    return status >= 200 && status < 300; // 只处理2xx状态码
  },
  timeout: 1000*60 // request timeout
})



//创建实例
const service = axios.create({
    baseURL: '/api/',
    maxRedirects:0,
    validateStatus: function (status) {
      // 这里可以自定义哪些状态码被认为是成功的
      return status >= 200 && status < 300; // 只处理2xx状态码
    },
    timeout: 1000*60 // request timeout
})

//配置拦截器
service.interceptors.request.use(
    (config) => {
      const pageurl = window.location.href;
      const paramStore = useParamStore();

      const redirectURL = paramStore.redirectURL;
      if(redirectURL != '' && redirectURL != null){
        config.headers['pageurl'] = redirectURL;
      }else{
        config.headers['pageurl'] = pageurl;
      }

      return config
    },
    (error) => {
      console.log(error) // for debug
      Promise.reject(error)
    }
)

//处理返回信息
service.interceptors.response.use(
    response => {
     
      if(response.data.code == 0){
        return response.data;
      }else{
        DialogTool.closeToast();
        DialogTool.showAlert(response.data.msg)
        return Promise.reject(response.data)
      }
        
    }, error => {
      let status = error.response.status;
      let data = error.response.data;

    
   
      if (status === 401) { //需要登录
        if (data.errorType === "NOT_LOGIN_CAS") {        
            //发现CAS未登录，跳转到CAS统一登录页面
            location.href = data.casLoginUrl
            return Promise.reject("401");
        }
        else {
            return Promise.reject(error)
        }
      } else {
           
            return Promise.reject(error)
      }
    });


    
    //封装get、post
    function post<T>(url:string,data_={}): Promise<ResultData<T>>{
       
        return service.post(url,data_);
    }

    function get<T,T1=any,T2=any>(url:string,params?:object):Promise<ResultData<T,T1,T2>>{
        return service.get(url,{params,maxRedirects:0});
    }
  
  export default {
    post,get,service
  }



  